const { DataTypes } = require('sequelize')
const sequelize = require('../config/database')

const UserThirdParty = sequelize.define('UserThirdParty', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '关联ID'
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '用户ID'
  },
  platform: {
    type: DataTypes.STRING(20),
    allowNull: false,
    comment: '平台类型（wework/dingtalk/feishu）'
  },
  platform_user_id: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '平台用户ID'
  },
  platform_user_info: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '平台用户信息（JSON格式）'
  },
  bind_time: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '绑定时间'
  },
  status: {
    type: DataTypes.TINYINT,
    allowNull: false,
    defaultValue: 1,
    comment: '状态（1正常 0解绑）'
  }
}, {
  tableName: 'user_third_parties',
  timestamps: true,
  indexes: [
    {
      fields: ['user_id'],
      name: 'user_third_parties_user_id_index'
    },
    {
      unique: true,
      fields: ['platform', 'platform_user_id'],
      name: 'user_third_parties_platform_unique'
    }
  ]
})

// 延迟设置关联关系，避免循环依赖
setTimeout(() => {
  const User = require('./user')
  UserThirdParty.belongsTo(User, {
    foreignKey: 'user_id',
    as: 'user'
  })
}, 0)

module.exports = UserThirdParty 